package cn.zhx.xa.service.exception;



import cn.zhx.xa.model.vo.common.Result;
import cn.zhx.xa.model.vo.common.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {



    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e){
        e.printStackTrace();
        return Result.build(null , 201,"出现了异常") ;
    }

    @ExceptionHandler(BusinessException.class)
    public Result handleBusinessException(BusinessException e){
        log.error("Business exception! The reason is:{}", e.getMessage());
        e.printStackTrace();
        return Result.build(null , e.getResultCodeEnum()) ;
    }

    /**
     * 处理MethodArgumentNotValidException异常
     *
     * @param e MethodArgumentNotValidException异常对象
     * @return Result<?> Result
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        // 创建一个StringBuilder对象用于拼接错误信息
        StringBuilder errorMsg = new StringBuilder();
        // 遍历所有字段错误
        e.getBindingResult().getFieldErrors().forEach(fieldError -> {
            // 将字段名和默认错误信息拼接到错误信息中
            errorMsg.append(fieldError.getField() + fieldError.getDefaultMessage()).append(",");
        });
        // 获取完整的错误信息
        String message = errorMsg.toString();
        log.error("MethodArgumentNotValidException exception! The reason is:{}", message);
        // 返回失败的ApiResult，将最后一个逗号去掉
        return Result.build(null, ResultCodeEnum.DATA_ERROR.getCode(),message.substring(0, message.length() - 1));
    }


}